import {Component, ElementRef, Input, EventEmitter, Output, OnInit, ViewChild, Injectable} from '@angular/core';
import {ConsultingPriceService} from "./consulting-price.service";
import {PurchaseListService} from "../purchase-list/purchase-list.service";
import {IPOlistService} from "../IPO-list/IPO-list.service";
import {FileUploadNormalComponent} from '../file-upload-normal/file-upload-normal.component';
import {environment} from '../../../../../environments/environment';
import {AppPaginationComponent} from '../../../../widgets/pagination/pagination.component';
import {InquiryTempComponent} from '../inquiry-template/inquiry-template.component';
import {newStockModel} from "./new-stock.model";
import {Util} from "../../../../common/util";
import * as _ from 'lodash';


/**
 * 网下新股发起询价
 */
@Component({
  selector: 'new-stock-purchase-consulting-price',
  templateUrl: './consulting-price.component.html',
  styleUrls: ['./consulting-price.component.scss'],
  providers: [ConsultingPriceService, PurchaseListService, IPOlistService]
})
export class ConsultingPriceComponent implements OnInit {

  public $ = window["$"];

  // 当前模态框类型 1.发起询价 2.查看申购明细
  public modalType = "";

  // 文件上传组件
  @ViewChild(FileUploadNormalComponent)
  public fileUploadNormalComponent: FileUploadNormalComponent;

  @Input()
  public lNewstockNo: string;

  // 按钮操作权限
  @Input()
  public operateList: any;

  // 关闭事件
  @Output()
  close: EventEmitter<boolean> = new EventEmitter<boolean>();

  // 记录页面是否有更新操作标记
  public hasUpdated: boolean = false;

  // 新股数据模型
  public newStockModel: any = newStockModel;

  public modalStatus: boolean;
  // 新股基本信息列表
  public newStockInfoList: Array<any>;
  // 询价明细列表
  public inquiryList: Array<any>;
  // 申购明细列表
  public sGList: Array<any>;
  // 中签明细列表
  public zQList: Array<any>;

  // 录入询价模态框存储数据
  public InquiryDetailModalData: any = {};

  // 基金选择模态框的查询条件对象
  public modalFundSearch: any = {
    fundCode: "",
    fundName: ""
  };

  // 基金选择模态框请求返回的基金数据对象
  public modalFundData: any;

  // 二级模态框（基金选择列表）内选中数据对象
  public checkedData = {};

  // 文件上传modal配置信息
  public fileUploadModal = {
    modalTile: "", // modal title
    title: "", // titel
    url: "", // url
    method: "", // POST OR GET
    itemAlias: "", // file alias
    formDatas: [] // POST 参数
  };

  @ViewChild("modal")
  public modal: ElementRef;

  // 询价列表查询条件
  public inquirySearchBody = {
    page: 1,
    pageSize: environment.pageSize,
    vcOperaterId: "",
    vcFundmrgId: ""
  };

  // 询价列表分页信息
  public inquiryPageInfo = {
    currentPageNum: 1,
    totalPages: 1
  };

  // 询价分页配置
  @ViewChild("inquiryPag")
  public inquiryPagComponent: AppPaginationComponent;

  // 下载询价模板
  @ViewChild(InquiryTempComponent)
  private inquiryTempComponent: InquiryTempComponent;

  // 申购列表查询条件
  public sgSearchBody = {
    page: 1,
    pageSize: environment.pageSize,
    vcOperaterId: "",
    vcFundmrgId: ""
  };

  // 申购列表分页信息
  public sgPageInfo = {
    currentPageNum: 1,
    totalPages: 1
  };

  // 申购分页配置
  @ViewChild("sgPag")
  public sgPagComponent: AppPaginationComponent;


  // 中签列表查询条件
  public zqSearchBody = {
    page: 1,
    pageSize: environment.pageSize,
    vcOperaterId: "",
    vcFundmrgId: ""
  };

  // 中签列表分页信息
  public zqPageInfo = {
    currentPageNum: 1,
    totalPages: 1
  };

  // 中签分页配置
  @ViewChild("zqPag")
  public zqPagComponent: AppPaginationComponent;

  /**
   * [constructor description]
   * @param {ConsultingPriceService} public consultingPriceService [询价Service]
   * @param {PurchaseListService}    public purchaseListService    [网下申购Service]
   */
  constructor(
    public iPOlistService: IPOlistService,
    public consultingPriceService: ConsultingPriceService,
    public purchaseListService: PurchaseListService
  ) {
  }

  ngOnInit() {
    Util.$("#dtHkDate").datepicker();
    // Util.$('#dtHkDate').datepicker({
    //   autoclose: true
    // });
  }

  ngAfterViewInit(): void {
    Util.datepickerPluginInit(".datepicker-plugin");
    // Util.$("#dtWxsgDate").val('20170623');
  }


  public openModal(type,lNewstockNo?): void {
    this.newStockModel.lNewstockNo = lNewstockNo;
    this.modalType = type;
    if (this.newStockModel.lNewstockNo) {
      this.loadStockInfoByNo();
    } else {
      this.select2PluginInit();
    }

    this.modalStatus = true;
    Util.$(this.modal.nativeElement).modal('show');
  }

  public closeModal(): void {
    this.close.emit(true); // 关闭后触发上层刷新事件
    this.modalStatus = false;
    Util.$(this.modal.nativeElement).modal('hide');
  }

  public toggleModal(): void {
    this.modalStatus = !this.modalStatus;
    Util.$(this.modal.nativeElement).modal('toggle');
  }


  /**
   * 初始化select2插件搜索下拉框
   */
  public select2PluginInit() {
    var that = this;
    var param = {
      pageSize: 0,
      page: 0
    };
    this.consultingPriceService.getNewstockInfoList(param)
      .subscribe((data) => {
        let vcNewstockIdList = [];
        if (data) {
          this.newStockInfoList = data.list;

          _.forEach(this.newStockInfoList, newStock => {
            let temp = {
              id: newStock.vcNewstockId,
              text: newStock.vcNewstockId
            };
            vcNewstockIdList.push(temp);
          });

        }

        // var data1 = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];

        Util.$('.vcNewstockId').select2({
          data: vcNewstockIdList,
          multiple: false,
          closeOnSelect: false
        });

        // 选项发生修改
        Util.$('.vcNewstockId').on("select2:select", function (evt) {
          // 获得id
          // that.newStockModel.vcNewstockId = evt.params.data.id;
          let _newStock = _.find(that.newStockInfoList, {vcNewstockId: evt.params.data.id});

          // 构建需要的值
          that.newStockModel.vcNewstockId = _newStock.vcNewstockId;
          that.newStockModel.vcNewstockName = _newStock.vcNewstockName;
          that.newStockModel.enIssuePrice = _newStock.enIssuePrice;
          that.newStockModel.enIssuesStock = _newStock.lIpoStock;
          that.newStockModel.dtWxsgDate = _newStock.dtWxsgDate;
          that.newStockModel.vcMarket = _newStock.vcMarket;
          that.newStockModel.vcLeadUnderwriter = _newStock.vcLeadUnderwriterName;
          console.log('选择的对象：' + JSON.stringify(that.newStockModel));
          // 其他基金基金助理是否有新增果，如果有 赋值实例ID
          that.consultingPriceService.getNewstockInfo(that.newStockModel.vcNewstockId).subscribe(data => {
            if (data.lNewstockNo) {
              that.newStockModel.lNewstockNo = data.lNewstockNo;

              // 页面隐藏下拉框
              Util.$(".select2").css("display", "none");
              Util.$(".select2-dropdown").css("display", "none");
            }


          });

          console.log('选择的对象：' + JSON.stringify(that.newStockModel));
        })
      });

  }


  /**
   * [getOperateByStatus 根据新股状态获得操作权限]
   * @param {[type]} operateId [1、编辑询价 2、导入询价 3、询价确认  4、编辑询价明细 5、编辑风控 6、代确认 7、申购确认 8、提交]
   * @param {[type]} vcNewstockStatus [新股状态]
   *
   * 备注：申购确认、编辑风控 暂时不做
   * TODO: 还可以再优化
   */
  canOperate(operateId, vcNewstockStatus) {
    // console.log("~~" + vcNewstockStatus + "," + operateId);
    // console.log(this.operateList);
    var retVale = false;

    let item: any = _.find(this.operateList, {vcItemKey: operateId});
    if (item && item.vcExtValue2) {
      if (_.indexOf(_.split(item.vcExtValue2, ","), vcNewstockStatus) > -1) {
        retVale = true;
      }
    }

    // return retVale;
    return true;
  }

  /**
   * [getNewstockInfoList 获取证劵信息]
   */
  public getNewstockInfoList() {
    var param = {
      page: 1,
      pageSize: 10
    };
    this.consultingPriceService.getNewstockInfoList(param).subscribe(data => {
      if (data && data.list) {
        this.newStockInfoList = data.list;
      }
    });
  }

  /**
   * [loadStockInfo 根据证券代码加载新股信息和参与的基金列表信息]
   */
  public loadStockInfo() {
    if (this.newStockModel.lNewstockNo) {
      this.consultingPriceService.getNewstockInfo(this.newStockModel.vcNewstockId).subscribe(data => {
        if (data) {
          console.log("询价接口返回数据：" + JSON.stringify(data));
          // 数据模型绑定
          this.newStockModel = data;

          if (this.newStockModel.lNewstockNo) { // 已发起询价
            this.getInquiryList(1); // 询价明细列表
            this.getSGList(1); // 申购明细列表
          }
        }
      });
    } else {
      this.newStockModel = _.find(this.newStockInfoList, {vcNewstockId: this.newStockModel.vcNewstockId});
    }
  }

  /**
   * [loadStockInfoByNo 根据实例ID加载新股信息和参与的询价列表信息]
   */
  public loadStockInfoByNo() {
    this.consultingPriceService.getNewstockInfoByNo(this.newStockModel.lNewstockNo).subscribe(data => {
      if (data) {
        console.log("询价接口返回数据：" + JSON.stringify(data));
        // 数据模型绑定
        this.newStockModel = data;

        // 数据单位转换： 预计中签率乘以100
        this.newStockModel.enPredictRate = this.newStockModel.enPredictRate * 100; // 预计中签率
        // 发行数量(万股)：
        this.newStockModel.lIpoStock = this.calculateMoney(data.lIpoStock/10000,'0,0.0000');

        if (this.newStockModel.lNewstockNo) { // 已发起询价
          this.getInquiryList(1); // 询价明细列表
          this.getSGList(1); // 申购明细列表
          this.getZQList(1); // 中签明细列表
        }
      }
    });
  }

  /**
   * 对指定文字、数字进行数字格式化
   * @param value 目标源
   * @param format 格式化格式，具体可以查看文档http://numeraljs.com
   * @param positive 是否启用正数 '+' 号表示，默认false，不启用
   * @param emptyStrWhenZero 目标源的值为0时，是否返回空字符串，默认false，不启用
   * @param enableFormatNull 当目标源的值为null时，是否允许进行格式化，默认false，不允许
   * @return 格式化后的数字字符串
   */
  calculateMoney(value: any, format: string = '0,0.00', positive: boolean = false,
    emptyStrWhenZero: boolean = false,enableFormatNull: boolean = false): string {
    if (isNaN(value)){
    return "";
    }
    if (value == null && !enableFormatNull) {
    return "";
    }
    if (emptyStrWhenZero && (parseFloat(value) === 0)) {
    return "";
    }
    return window['numeral'](value).format(positive ? '+' + format : format);
  }

  // 对转义后的金额还原
  reCalculateMoney(data){
    if(data==""){
      return "";
    }
    if(data.charAt(data.length-1) == "." ){
      return data.substring(0, data.length - 1) + '0000';
    }
    if(!(data.includes("."))){
      return data + '0000';
    }
    var arr = _.without(data.split(""),',','.');
    var str = "";
    for (var i =0 ; i < arr.length; i++){
      str += arr[i];
    }
    return str;
  }


  /**
   * [getInquiryList 询价明细列表 根据实例Id（lNewstockNo）查询询价明细信息。操作员Id和基金经理Id作为过滤条件。]
   */
  public getInquiryList(pageNum) {
    this.inquirySearchBody.page = pageNum;
    this.iPOlistService.getInquiryList(this.inquirySearchBody, this.newStockModel.lNewstockNo).subscribe(data => {
      if (data) {
        this.inquiryList = data.list;

        _.forEach(this.inquiryList, data => {
          // 为每条询价详细添加是否可编辑状态
          data.isEdited = false;
          // 备份询价价格, 用于询价详细取消修改恢复原来的值
          data.enPriceOld = data.enPrice;
          // 备份询价数量, 用于询价详细取消修改恢复原来的值
          data.lSharesOld = data.lShares;
        });

        // 构建分页
        var temp = {
          currentPageNum: data.pageNum,
          totalPages: data.pages,
        };
        this.inquiryPageInfo = temp;
      }

    });
  }

  /**
   * [getSGListById 申购基金列表]
   */
  public getSGList(pageNum) {
    this.sgSearchBody.page = pageNum;
    this.purchaseListService.getSGList(this.sgSearchBody, this.newStockModel.lNewstockNo).subscribe(data => {
      if (data) {
        this.sGList = data.list;

        // 构建分页
        var temp = {
          currentPageNum: data.pageNum,
          totalPages: data.pages,
        };
        this.sgPageInfo = temp;
      }

    });
  }

  /**
   * [getZQList 中签明细列表]
   */
  public getZQList(pageNum) {
    // this.purchaseListService.getZQList(this.newStockModel.lNewstockNo).subscribe(data => {
    //   //console.log("中签明细列表：" + JSON.stringify(data));
    //   this.zQList = data;
    // });

    this.zqSearchBody.page = pageNum;
    this.purchaseListService.getZQList(this.zqSearchBody, this.newStockModel.lNewstockNo).subscribe(data => {
      if (data) {
        this.zQList = data.list;

        // 构建分页
        var temp = {
          currentPageNum: data.pageNum,
          totalPages: data.pages,
        };

        this.zqPageInfo = temp;
      }

    });
  }

  /**
   * [saveNewStock 新增新股询价]
   */
  public saveNewStock() {
    var that = this;
    window["swal"]({
        title: "提示",
        text: "是否确定要更新新股信息?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) { // 确认
          // 缴款时间 格式转化成 yyymmdd
          let _dtWxsgDate = Util.$("#dtWxsgDate").val();
          that.newStockModel.dtWxsgDate = _dtWxsgDate.replace(/-/g, "");

          // 数据单位转换： 预计中签率乘以100
          // this.newStockModel.enPredictRate = this.newStockModel.enPredictRate / 100;
          // 数据单位转换： 市值门槛除以10000
          // this.newStockModel.enMinivalue = this.newStockModel.enMinivalue * 10000;

          that.consultingPriceService.addNewStock(that.newStockModel).subscribe(data => {
            if (data) {
              that.newStockModel.lNewstockNo = data.lNewstockNo;
              window["swal"]("新增成功", "", "success")
            }
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  /**
   * [submitNewStock 提交证券信息]
   */
  public submitNewStock() {
    var that = this;
    // 新股状态为0，即录入询价信息
    if (that.newStockModel.vcNewstockStatus !== "0") {
      return window["swal"]("提示", "数据已经提交，不能重复提交", "warning");
    }
    var that = this;
    window["swal"]({
        title: "提示",
        text: "是否确定要提交证券信息?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) { // 确认
          that.consultingPriceService.submitNewStock(that.newStockModel).subscribe(result => {
            if (result) {
              if (result.code === 0) {
                window["swal"]("提示",
                  `${result.data.averagevalueStr == undefined ? "" : result.data.averagevalueStr}\n
                   ${result.data.fundInfoStr == undefined ? "" : result.data.fundInfoStr}\n
                   ${result.data.maxAmountStr == undefined ? "" : result.data.maxAmountStr}\n
                   ${result.data.reftraceStr == undefined ? "" : result.data.reftraceStr}\n
                   ${result.data.successCount == undefined ? "" : result.data.successCount}`, "info");
              }
              that.newStockModel.lNewstockNo = result.lNewstockNo;
              that.closeModal();
            }
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  /**
   * [updateNewStock 更新新股询价]
   */
  public updateNewStock() {
    var that = this;
    window["swal"]({
        title: "提示",
        text: "是否确定要更新股新信息?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) { // 确认
          // 缴款时间 格式转化成 yyymmdd
          let lJkDate = window["$"]("#lJkDate").val();
          if (lJkDate !== "" && lJkDate != undefined) {
            that.newStockModel.lJkDate = lJkDate.replace(/-/g, "");
          }
          that.newStockModel.enPredictRate = that.newStockModel.enPredictRate / 100; // 重设预计中签率
          that.newStockModel.lIpoStock = that.reCalculateMoney(that.newStockModel.lIpoStock); // 重设发行数量

          that.consultingPriceService.updateNewStock(that.newStockModel).subscribe(data => {
            if (data) {
              that.newStockModel.lNewstockNo = data.lNewstockNo;
              window["swal"]("更新成功", "", "success");
              that.closeModal();
            }
          });
        } else { // 取消
          //window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  /**
   * [toggleconfigurationSaleModalOpen 打开导入询价modal]
   */
  toggleconfigurationSaleModalOpen() {
    // 配置导入文件信息
    this.fileUploadModal = {
      modalTile: "导入询价",
      title: "请选择上传询价",
      url: environment.server + "otc/v1/Newstock/InquiryList/" + this.newStockModel.lNewstockNo,
      method: "POST",
      itemAlias: "file",
      formDatas: [
        {
          key: "skip",
          value: true
        }
      ]
    };

    this.fileUploadNormalComponent.openModal();
  }

  /**
   * [toEdit 置询价明细为修改状态
   *   1.有传入实例，对单个实例标记
   *   2.没有传入实例， 对列表的所有实例标记
   * ]
   * @param {[type]} inquiryList [询价明细实例]
   */
  toEdit(inquiryList) {
    _.forEach(inquiryList, data => {
      data.isEdited = true;
    });
  }


  /**
   * [saveInqurify 保存询价明细]
   * @param {[type]} inquiryList [询价明细实例列表]
   */
  saveInqurify(inquiryList) {
    // 校验 冻结金额不能大于基金当前规模
    var checkResult = this.checkInqurify(inquiryList);

    if (checkResult !== "") {
      window["swal"]("提示", checkResult + ",冻结金额不能大于基金当前规模", "error");
    } else {
      this.saveInqurifyList(inquiryList);
    }
  }

  // 删除询价明细
  deleteInqurify(inquiryList) {
    const param = {
      pmkyList: inquiryList[0].pmkyNum
    };
    return this.consultingPriceService.deleteInqurify(param).subscribe(result => {
      if (result) {
        if (result.code === 0) {
          window["swal"]("成功", "删除明细成功", "success");
          this.loadStockInfoByNo();
        }
      }
    });
  }

  /**
   * [saveInqurifyList 保存询价明细,对列表的所有实例保存]
   * @param {[type]} inquiryList [询价明细实例列表]
   */
  saveInqurifyList(inquiryList) {
    var that = this;
    // 基金名称
    var vcFundNames = "";
    // 需要更新的实例
    var _inquiryList: any = _.filter(inquiryList, {isEdited: true});

    var param = [{
      pmkyNum: _inquiryList[0].pmkyNum,
      vcFundCode: _inquiryList[0].vcFundCode,
      lShares: _inquiryList[0].lShares,
      cIsJoin: _inquiryList[0].cIsJoin,
      lNewstockNo: _inquiryList[0].lNewstockNo,
      enAveragevalue: _inquiryList[0].enAveragevalue,
      vcBank: _inquiryList[0].vcBank
    }]

    // 获得列表所有基金名称
    _.forEach(_inquiryList, inquiry => {
      vcFundNames += (vcFundNames == "" ? inquiry.vcFundName : "、" + inquiry.vcFundName);
    })

    window["swal"]({
        title: "提示",
        text: "是否保存对：" + vcFundNames + "，询价明细修改?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) { // 确认
          _.forEach(_inquiryList, inquiry => {
            // 移除辅助的属性
            delete inquiry.isEdited;
            delete inquiry.enPriceOld;
            delete inquiry.lSharesOld;
          });

          that.consultingPriceService.saveInqurify(param, true).subscribe(result => {
            if (result) {
              if (result.code === 0) {
                window["swal"]("提示", "保存成功", "success");
                _.forEach(_inquiryList, inquiry => {
                  // 重新给辅助属性赋值
                  inquiry.isEdited = false;
                  inquiry.enPriceOld = inquiry.enPrice;
                  inquiry.lSharesOld = inquiry.lShares;
                });
              }
              if (result.code === 1006) {
                window["swal"]({
                    title: "提示",
                    text: result.detailMsg,
                    type: "info",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    cancelButtonText: "取消",
                    closeOnConfirm: true,
                    closeOnCancel: true,
                    showLoaderOnConfirm: true
                  },
                  function (isConfirm) {
                    if (isConfirm) {
                      that.consultingPriceService.saveInqurify(param, false).subscribe(result => {
                        if (result.code === 0) {
                          setTimeout(`window["swal"]("提示", "保存成功", "success")`, 1000);
                        }
                      });
                    }
                  });
              }
            }
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  /**
   * [checkInqurify 保存询价明细前，校验冻结金额不能大于基金当前规模
   * 返回空，验证通过；否则返回验证不通过基金名称]
   * @param {[type]} inquiryList [询价明细实例列表]
   */
  checkInqurify(inquiryList) {
    var retVal = "";
    _.forEach(inquiryList, inquiry => {
      // 冻结金额 大于 基金当前规模
      if (inquiry.fundsacle < inquiry.enPredictMoney) {
        retVal += (retVal == "" ? inquiry.vcFundName : "、" + inquiry.vcFundName);
      }
    });

    return retVal;
  }

  /**
   * [cancelEdit 取消修改]
   * @param {[type]} inquiry [询价明细实例]
   */
  cancelEdit(inquiryList) {
    var that = this;
    // 基金名称
    var vcFundNames = "";
    // 需要更新的实例
    var _inquiryList: any = _.filter(inquiryList, {isEdited: true});

    // 获得列表所有基金名称
    _.forEach(_inquiryList, inquiry => {
      vcFundNames += (vcFundNames == "" ? inquiry.vcFundName : "、" + inquiry.vcFundName);
    });

    window["swal"]({
        title: "提示",
        text: "是否取消对:" + vcFundNames + ",询价明细修改?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) {
          // 重置回原来的 询价价格、询价数量
          _.forEach(_inquiryList, inquiry => {
            inquiry.enPrice = inquiry.enPriceOld;
            inquiry.lShares = inquiry.lSharesOld;
            inquiry.isEdited = false;
          });
        }
      });
  }

  /**
   * [calculateEnMoney 计算询价金额]
   * @param {[type]} inquiry [询价明细实例]
   */
  calculateEnMoney(inquiry) {
    var retVal = "";
    if (inquiry.enPrice != null && inquiry.lShares != null) {
      // 询价金额 = 询价数量 * 询价数量
      inquiry.enMoney = inquiry.enPrice * inquiry.lShares;
      retVal = inquiry.enMoney;
    }

    return retVal;
  }

  /**
   * [calculateEnPredictMoney 计算预计冻结金额]
   * @param {[type]} inquiry       [询价明细实例]
   * @param {[type]} enPredictRate [预计中签率]
   */
  calculateEnPredictMoney(inquiry, enPredictRate) {
    var retVal = "";
    if (enPredictRate != null && inquiry.enPrice != null && inquiry.lShares != null) {
      // 预计冻结金额=询价金额 * 预计中签率
      inquiry.enPredictMoney = inquiry.enPrice * inquiry.lShares * _.toNumber(enPredictRate);
      retVal = inquiry.enPredictMoney
    }

    return retVal;
  }

  /**
   * [toggleInquiryTempModalOpen 下载询价模板]
   */
  toggleInquiryTempModalOpen() {
    this.inquiryTempComponent.openModal();
  }

  /**
   * [reflesh 刷新询价列表]
   * @param {[type]} event [description]
   */
  reflesh(event?) {
    if (event) {
      this.hasUpdated = true;
      // 刷新询价列表
      this.getInquiryList(1);
    }
  }

  // 打开录入询价模态框
  writingInquiryList() {
    this.$("#InquiryDetailModal").modal('show');
  }

  // 打开基金选择模态框并查询
  public openChooseFundModal(item) {
    this.searchFundList();
    this.$("#chooseFundModal").modal('show');
  }

  // 基金选择模态框查询函数
  public searchFundList() {
    const param = {
      lNewstockNo: this.newStockModel.lNewstockNo,
      fundCode: this.modalFundSearch.fundCode ? this.modalFundSearch.fundCode : '',
      fundName: this.modalFundSearch.fundName ? this.modalFundSearch.fundName : '',
      type: 2,
      pageSize: 10000,
      page: 1
    };
    this.consultingPriceService.searchFundList(param).subscribe(result => {
      if (result != null) {
        this.modalFundData = result;
      }
    });
  }

  // 基金选择模态框切换选中状态
  fundChooseChecked(item, $event) {
    if ($event.target.checked) {
      this.checkedData = item.vcFundCode;
    }
  }

  // 基金选择模态框确定按钮，将选择的组合代码和股票代码进行查询询价信息并返回到上一级模态框中
  public confirmFund() {
    const param = {
      vcFundCode: this.checkedData,
      lNewStockNo: this.newStockModel.lNewstockNo
    };
    return this.consultingPriceService.InquiryFundInfo(param).subscribe(result => {
      if (result) {
        if (result.code === 1005){
          window["swal"]("提示", result.detailMsg, "info");
        }
        if (result.code === 0){
          this.InquiryDetailModalData = this.$.extend(true, {}, result.data);
          this.$("#chooseFundModal").modal('hide');
        }
      }
    });
  }

  // 基金选择模态框关闭，并清空数据
  public closeFundModal() {
    this.modalFundSearch = {
      fundCode: "",
      fundName: ""
    };
    this.$("#chooseFundModal").modal('hide');
  }

  // 保存询价明细
  public saveInquiryDetail() {
    const that = this;
    const param = {
      lNewstockNo: that.newStockModel.lNewstockNo,
      data: [that.InquiryDetailModalData]
    }
    return that.consultingPriceService.saveInquiryFundInfo(param, true).subscribe(result => {
      if (result) {
        if (result.code === 0) {
          window["swal"]("提示", "保存成功", "success");
          that.getInquiryList(1);
          that.InquiryDetailModalData = {};
        }
        if (result.code === 1006) {
          window["swal"]({
              title: result.msg,
              text: result.detailMsg,
              type: "info",
              showCancelButton: true,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              closeOnConfirm: true,
              closeOnCancel: true,
              showLoaderOnConfirm: true
            },
            function (isConfirm) {
              if (isConfirm) {
                return that.consultingPriceService.saveInquiryFundInfo(param, false).subscribe(result => {
                  if (result.code === 0) {
                    window["swal"]("提示", "保存成功", "success");
                    that.getInquiryList(1);
                    that.InquiryDetailModalData = {};
                  }
                });
              }
            });
        }
      }
    });
  }

  public closeSaveInquiryDetail(){
    this.InquiryDetailModalData = {};
  }
}
